<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Agency extends Manage_Controller
{
	public $agencys = array();
	public $agency = array();

	public function __construct()
	{
		parent::__construct();

		//如果不是中介公司的经纪人，没有权限继续操作
		//!$this->user['agencyid'] && showmsg('没有权限操作');

		//$this->load->model('second_model');

		//查询我可以管理的中介公司、店铺
		//$this->agencys = $this->_get_agencys();
		//var_dump($this->agencys);
		//查询我的中介公司
		//$this->agency = $this->second_model->get_agency_by_adminname(null, 1, 0)->row_array();
		//$this->agency = $this->_get_agency();
	}

	/**
	 * 中介管理首页（显示一些基本信息和统计信息）
	 */
	public function index()
	{
		$this->load->view('manage/agency_index', $this->data);
	}

	/**
	 * 添加分店
	 */
	public function add()
	{
		$this->load->view('manage/agency_add', $this->data);
	}

	/**
	 * 分店权限设置
	 */
     public function set()
     {
        $this->load->view('manage/agency_set', $this->data);
     }

	/**
	 * 添加分店
	 */
	/*
	* public function add()
	* {
	* !$this->agency && showmsg('您没有权限操作');

	* if ($_POST)
	* {
	* $post = $this->input->post(null, true);
	* $post['name'] = trim($post['name']);
	* $post['adminname'] = trim($post['adminname']);
	* $post['postremainder'] = intval($post['postremainder']);

	* $post['postremainder'] < 0 && showmsg('输入的数量不能小于0');
	* $post['postremainder'] > $this->agency['postremainder'] && showmsg('公司剩余数量不够分配，请重新操作');
	* empty($post['name']) && showmsg('分店名称不能为空');
	* empty($post['adminname']) && showmsg('管理员帐号不能为空');

	* $post['parentid'] = $this->agency['agencyid']; //父id
	* $post['posttype'] = $this->agency['posttype']; //发布权限类型
	* $post['createtime'] = time(); //创建时间
	* $this->agency['posttype'] != 'total' && $post['expiredtime'] = $this->agency['expiredtime']; //过期时间

	* //管理员账号不为空的话检查用户是否存在
	* $this->_check_username($post['adminname']);

	* //添加分店
	* $this->second_model->insert_agency($post);

	* //扣除发布数
	* if ($post['postremainder'] != 0)
	* {
	* $this->second_model->set_agency('postremainder', -$post['postremainder'], $this->agency['agencyid']);
	* }

	* redirect('manage/agency/son');
	* }
	* }
	*/

	/**
	 * 修改自身资料
	 */
	public function edit($agencyid)
	{
		//根据登录用户查询的店铺资料，如果该店铺资料为空则没有权限
		if (!$this->agencys[$agencyid])
		{
			showmsg('您没有权限操作');
		}

		if ($_POST)
		{
			$post = $this->input->post(null, true);
			$post['name'] = trim($post['name']);
			$post['adminname'] = trim($post['adminname']);

			empty($post['name']) && showmsg('分店名称不能为空');
			empty($post['adminname']) && showmsg('管理员帐号不能为空');
			$this->_check_username($post['adminname']);

			//var_dump($_FILES);exit;

			//上传
			if ($_FILES['icon']['error'] == 0 || $_FILES['bgimg']['error'] == 0)
			{
				$agency = $this->second_model->get_agency_by_id($agencyid)->row_array();
				foreach ($_FILES as $k => $v)
				{
					$file = $this->_upload($k);
					$post[$k] = set_attachs_path($file['full_path']);
					//删除上次上传的文件
					$filename = get_attachs_allpath($agency[$k]);
					if (file_exists($filename) && is_readable($filename)) @unlink($filename);
				}
			}
			//更新
			$this->second_model->update_agency($post, $agencyid);

			redirect('manage/agency/edit/' . $agencyid);
		}
		else
		{
			$agency = $this->second_model->get_agency_by_id($agencyid)->row_array();

			$data = array();
			$data['agency'] = $agency;
			$this->load->view('home/manage/agency_edit', $data);
		}
	}

	/**
	 * 分店发布数量分配
	 *
	 */
	public function editpost()
	{
		!$this->agency && showmsg('您没有权限操作');

		if ($this->agency['posttype'] != 'total')
		{
			showmsg('只有发布类型是固定数量的中介公司才允许此操作');
		}

		if ($_POST)
		{
			$postnums = $this->input->post('postnums', true);
			$postnums_tmp = array();

			//数据处理
			$agencys = $this->second_model->get_agency_son($this->agency['agencyid'])->result_array();
			foreach ($agencys as $agency)
			{
				$key = $agency['agencyid']; //agencyid
				$postnum = intval($postnums[$key]); //提交过来的值
				if ($postnum != 0)
				{
					//如果较少的数量大于剩余声量，则把剩余数量全部减去
					if ($postnum < 0 && $agency['postremainder'] < abs($postnum))
					{
						$postnum = -$agency['postremainder'];
						//showmsg('[' . $agency['name'] . '] 减少的数量大于的剩余数量，请重新操作');
					}
					$postnums_tmp[$key] = $postnum;
				}
			}

			//添加减少的数量之和
			$postremainder = array_sum($postnums_tmp);

			if ($this->agency['postremainder'] < $postremainder)
			{
				showmsg('公司剩余数量不够分配，请重新操作');
			}

			//循环更新分店
			foreach ($postnums_tmp as $key => $postnum)
			{
				if ($postnum != 0)
				{
					$this->second_model->set_agency('postremainder', $postnum, $key);
				}
			}

			if ($postremainder != 0)
			{
				$this->second_model->set_agency('postremainder', -$postremainder, $this->agency['agencyid']);
			}
		}

		redirect('manage/agency/son');
	}

	/**
	 * 分公司列表
	 */
	public function son()
	{
		!$this->agency && showmsg('您没有权限操作');

		$data = array();
		//获取所有分店列表
		$data['agencys'] = $this->second_model->get_agency_son($this->agency['agencyid'])->result_array();
		$this->load->view('home/manage/agency_son', $data);
	}

	/**
	 * 修改分公司资料
	 */
	public function sonedit()
	{

	}

	/**
	 * 经纪人列表
	 */
	public function broker()
	{
		!$this->agencys && showmsg('您没有权限操作');

		$agencyid = $this->input->get('agencyid', true);
		$page = $this->input->get('page', true);
		$username = $this->input->get('username', true); //用户名
		$nickname = $this->input->get('nickname', true); //昵称
		$mobile = $this->input->get('mobile', true); //手机号码
		$ifactive = $this->input->get('ifactive', true); //用户状态
		$ifactive = $ifactive !== false ? $ifactive : -1; //用户状态默认为-1

		//如果是总店铺的管理员
		if ($this->agency['agencyid'])
		{
			//获取所有的店铺
			$agencys = $this->second_model->get_agency_son($this->agency['agencyid'])->result_array();
		}
		else
		{
			$agencys = $this->agencys;
		}

		//获取店铺的id
		$agencyids = $this->_get_agencyids($agencyid, $agencys);

		//查询条件
		$map = array();
		$username && $map['username'] = $username;
		$nickname && $map['nickname'] = $nickname;
		$mobile && $map['mobile'] = $mobile;
		$ifactive >= 0 && $map['ifactive'] = $ifactive;
		$map['agencyid'] = $agencyids;

		//var_dump($map);

		//分页查询字符串组合
		$query_str = '?';
		foreach ($map as $field => $v)
		{
			if (is_array($v)) continue;
			$query_str .= '&' . $field . '=' . $v;
		}

		$count = $this->auth->get_user_count_all($map); //查询总数
		$base_url = $this->uri->uri_string() . $query_str; //翻页的基础url
		$per_page = 20; //每页显示多少条数据
		$this->_set_pagination($base_url, $count, $per_page);

		//总页数
		$total_pages = ceil($count / $per_page);
		//当前页数
		$page > $total_pages && $page = $total_pages;
		($page <= 0 || !is_numeric($page)) && $page = 1;
		$offset = ($page - 1) * $per_page;

		//查询
		$users = array();
		$count && $users = $this->auth->get_UserData_all($map, $per_page, $offset)->result_array();

		$data = array();
		$data['users'] = $users; //查找的用户数组
		$data['agencyid'] = $agencyid; //中介店铺id
		$data['agencys'] = $agencys; //该中介的店铺
		$data['get'] = array(
			'agencyid' => $agencyid,
			'username' => $username,
			'nickname' => $nickname,
			'mobile' => $mobile,
			'ifactive' => $ifactive,
			);
		$this->load->view('home/manage/agency_broker', $data);
	}

	/**
	 * 经纪人资料
	 */
	public function brokerinfo()
	{
		$userid = $this->input->get('userid');
		if ($userid)
		{
			//登录后也会查询用户的数据
			//如果用户的id和已经查询过的用户id是一样的，直接赋值，不用再错一次查询
			if ($userid == $this->user['userid'])
			{
				$user = $this->user;
			}
			else
			{
				$map = array('userid' => $userid);
				$user = $this->auth->get_UserData($map)->row_array();
			}
		}
		//var_dump($this->agencys);
		if (!isset($this->agencys[$user['agencyid']]) && !$this->agency) showmsg('您没有权限查看该经纪人资料');

		$data = array();
		$data['userid'] = $userid;
		$data['user'] = $user;
		$this->load->view('home/manage/agency_brokerinfo', $data);
	}

	/**
	 * 添加经纪人
	 */
	public function brokeradd()
	{
		!$this->agencys && showmsg('您没有权限操作');

		if ($_POST)
		{
			//收集数据
			$post = $this->input->post(null, true);
			$post['groupid'] = 1;

			if ($post['password'] != $post['confirm_password'])
			{
				showmsg('确认密码和密码不同');
			}
			unset($post['confirm_password']);

			//用户名唯一检查
			if ($this->auth_model->get_user_by_username($post['username'])->num_rows() > 0)
			{
				showmsg('该用户帐号已存在');
			}

			//用户名唯一检查
			if ($this->auth_model->get_user_by_email($post['email'])->num_rows() > 0)
			{
				showmsg('该用户邮箱已存在');
			}

			//添加用户
			$this->auth->insert_user($post);

			//跳转到经纪人列表
			redirect('manage/agency/broker');
		}
		else
		{
			//如果是总店铺的管理员,获取所有的店铺
			if ($this->agency['agencyid'])
			{
				$agencys = $this->second_model->get_agency_son($this->agency['agencyid'])->result_array();
			}
			else
			{
				$agencys = $this->agencys;
			}

			$data = array();
			$data['agencys'] = $agencys;
			$this->load->view('home/manage/agency_brokeradd', $data);
		}
	}

	/**
	 * 获取店铺的ids
	 */
	private function _get_agencyids($agencyid, $agencys)
	{
		if ($agencyid)
		{
			$agencyids = $agencyid;
		}
		else
		{
			$agencyids = array();
			//如果用户是总店铺的管理员，则查询全部子店铺的id
			if ($this->agency['agencyid'])
			{
				foreach ($agencys as $agency)
				{
					$agencyids[] = $agency['agencyid'];
				}
			}
			//如果不是，则获取有权限管理的店铺id
			else
			{
				$agencyids = array_keys($this->agencys);
			}
		}

		return $agencyids;
	}

	/**
	 * 分页配置
	 */
	private function _set_pagination($base_url = null, $total_rows = null, $per_page = null)
	{
		//Load library
		$this->load->library('pagination'); //分页类
		//分页配置
		$config['base_url'] = site_url($base_url);
		; //基本url
		$config['total_rows'] = $total_rows; //总数据条数
		$config['per_page'] = $per_page; //每页显示多少条数据
		$config['use_page_numbers'] = true; //启用后显示的是当前页码
		$config['num_links'] = 3; //左右的数字
		//$config['uri_segment'] = 5; //URI 的哪个部分包含页数
		$config['page_query_string'] = true;
		$config['query_string_segment'] = 'p'; //传递页数的查询字符串
		$config['full_tag_open'] = '<div class="pages">';
		$config['full_tag_close'] = '</div>';
		$config['prev_link'] = '&laquo;'; //上一页文字
		$config['next_link'] = '&raquo;'; //下一页文字
		$config['cur_tag_open'] = '<b>'; //当前页开始
		$config['cur_tag_close'] = '</b>'; //当前页结束
		//初始化分页类
		$this->pagination->initialize($config);
	}

	/**
	 * 获取以id为键名的agencys
	 */
	private function _get_agencys()
	{
		$agencys_db = $this->second_model->get_agency_by_adminname()->result_array();
		$agencys = array();
		foreach ($agencys_db as $agency)
		{
			$agencys[$agency['agencyid']] = $agency;
		}
		return $agencys;
	}

	/**
	 * 获取总的中介公司资料 而非 分店（仅有一个）
	 * 父id为0的即时总的中介公司，父id不为0的即时店铺
	 */
	private function _get_agency()
	{
		$agency = array();
		foreach ($this->agencys as $agency)
		{
			if ($agency['parentid'] == 0)
			{
				return $agency;
			}
		}
	}

	/**
	 * 检查用户是否存在
	 *
	 * 用于添加、修改中介管理员的时候检查使用
	 */
	private function _check_username($username)
	{
		$this->load->model('auth_model');
		if ($this->auth_model->get_user_by_username($username)->num_rows() <= 0)
		{
			showmsg('用户名不存在');
		}
	}

	/**
	 * 文件上传
	 */
	private function _upload($field)
	{
		//创建上传目录
		$this->load->helper('directory');
		$upload_path = FCPATH . $this->config->item('attachs') . 'agency/' . date('ym') . '/';
		directory_create($upload_path);

		//上传配置
		$config = array();
		$config['upload_path'] = $upload_path;
		$config['allowed_types'] = 'gif|jpg|jpeg|png';
		$config['max_size'] = '200';
		$config['encrypt_name'] = true;

		$this->load->library('upload', $config);

		!$this->upload->do_upload($field) && showmsg($this->upload->display_errors('', ''));

		return $this->upload->data();

	}
}

/* End of file agency.php */
/* Location: ./application/controllers/manage/agency.php */
